<?php

namespace app\admin\controller\auth;

use app\admin\model\AuthDepartment;
use app\common\controller\Backend;
use think\Db;
use fast\Tree;
/**
 * 部门管理
 *
 * @icon fa fa-circle-o
 */
class Department extends Backend
{
    
    /**
     * Department模型对象
     * @var \app\admin\model\AuthDepartment
     */
    protected $model = null;

    protected $groupdata = [];
    //当前登录管理员所有子组别
    protected $childrenGroupIds = [];
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\AuthDepartment;
        $this->view->assign("deleteStatusList", $this->model->getDeleteStatusList());
        $this->childrenGroupIds = $this->auth->getChildrenGroupIds(true);
        $groupList = collection(AuthDepartment::field('*,parentid as pid')->select())->toArray();
        Tree::instance()->init($groupList);
        $result = [];
        if ($this->auth->isSuperAdmin())
        {
            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
        }
        else
        {
            $groups = $this->auth->getGroups();
            foreach ($groups as $m => $n)
            {
                $result = array_merge($result, Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['pid'])));
            }
        }
        $groupName = [];
        foreach ($result as $k => $v)
        {
            $groupName[$v['id']] = $v['name'];
        }
        $this->groupdata = $groupName;
        $this->assignconfig("admin", ['id' => $this->auth->id, 'group_ids' => $this->auth->getGroupIds()]);
        $this->view->assign('groupdata', $this->groupdata);
    }

    public function getChildrenGroupIds($withself = false)
    {
        //取出当前管理员所有的分组
        $groups = $this->getGroups();
        $groupIds = [];
        foreach ($groups as $k => $v) {
            $groupIds[] = $v['id'];
        }
        // 取出所有分组
        $groupList = \app\admin\model\AuthDepartment::where(['delete_status' => 0])->field('*,parentid as pid')->select();
        $objList = [];
        foreach ($groups as $K => $v) {
            if ($v['rules'] === '*') {
                $objList = $groupList;
                break;
            }
            // 取出包含自己的所有子节点
            $childrenList = Tree::instance()->init($groupList)->getChildren($v['id'], true);
            $obj = Tree::instance()->init($childrenList)->getTreeArray($v['pid']);
            $objList = array_merge($objList, Tree::instance()->getTreeList($obj));
        }
        $childrenGroupIds = [];
        foreach ($objList as $k => $v) {
            $childrenGroupIds[] = $v['id'];
        }
        if (!$withself) {
            $childrenGroupIds = array_diff($childrenGroupIds, $groupIds);
        }
        return $childrenGroupIds;
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax())
        {
            $list = AuthDepartment::all(array_keys($this->groupdata));
            $list = collection($list)->toArray();
            $list = $this->updateKey($list,'parentid','pid');
            $groupList = [];
            foreach ($list as $k => $v)
            {
                $groupList[$v['id']] = $v;
            }
            $list = [];
            foreach ($this->groupdata as $k => $v)
            {
                if (isset($groupList[$k]))
                {
                    $groupList[$k]['name'] = $v;
                    $list[] = $groupList[$k];
                }
            }
            $total = count($list);
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false) {
                        //添加成功
                        $params['id'] = $this->model->id;
                        $res = AuthDepartment::addDep($params);
                        if($res['errcode'] > 0)
                        {
                            $this->del($this->model->id);
                            $this->error($res['msg']);
                        }
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row)
            $this->error(__('No Results were found'));
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a", [], 'strip_tags');
            // 父节点不能是它自身的子节点
            if (!in_array($params['parentid'], $this->childrenGroupIds))
            {
                $this->error(__('The parent group can not be its own child'));
            }

            $parentmodel = model("AuthDepartment")->get($params['parentid']);
            if (!$parentmodel)
            {
                $this->error(__('The parent group can not found'));
            }
            if ($params)
            {
                $res = AuthDepartment::updateDep($ids,$params);
                if($res['errcode'] > 0)
                {
                    $this->error($res['msg']);
                }
                $row->save($params);
                //
                $this->success();
            }
            $this->error();
            return;
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids)
        {
            $ids = explode(',', $ids);
            $grouplist = $this->auth->getGroups();
            $group_ids = array_map(function($group) {
                return $group['id'];
            }, $grouplist);
            // 移除掉当前管理员所在组别
            $ids = array_diff($ids, $group_ids);

            // 循环判断每一个组别是否可删除
            $grouplist = $this->model->where('id', 'in', $ids)->select();
            foreach ($grouplist as $k => $v)
            {
                // 当前组别下有子组别
                $groupone = $this->model->get(['parentid' => $v['id']]);
                if ($groupone)
                {
                    $ids = array_diff($ids, [$v['id']]);
                    continue;
                }
            }
            if (!$ids)
            {
                $this->error(__('不能删除包含子部门和管理员的组'));
            }
            $data =  AuthDepartment::deleteDep($ids[0]);
            if($data['errcode'] > 0 )
            {
                $this->error(GetErrorLang($data['errcode']));
            }
            $count = $this->model->where('id', 'in', $ids)->delete();
            if ($count)
            {
                $this->success();
            }
        }
        $this->error();
    }

    /**
     * 批量更新
     */
    public function updateall()
    {
        $data = AuthDepartment::DepList();
        if($data['errcode']> 0)
        {
            return json(['code'=>2,'msg'=>'更新失败','url'=>'/admin/auth/department/index','wait'=>3]);
        }
        Db::execute('truncate table `hdyj_auth_department`');
        $dept = new AuthDepartment();
        $dept->saveAll($data['department'],false);
        return json(['code'=>1,'msg'=>'更新成功','url'=>'/admin/auth/department/index','wait'=>3]);
    }

    public function updateKey($data,$filed,$fileds)
    {
        $array = [];
        foreach ($data as $value)
        {
            $value[$fileds] =  $value[$filed];
            unset($value[$filed]);
            $array[] = $value;
        }
        return $array;
    }

    /**
     * 搜索下拉列表
     */
    public function searchlist()
    {
        $dept = GetBaseInfo('Dept');
        $groupList = collection(AuthDepartment::field('*,parentid as pid')->where('id','in',''.implode(',',$dept).'')->whereOr('parentid','in',''.implode(',',$dept).'')->select())->toArray();
        Tree::instance()->init($groupList);
        //权限
        $this->RoleFinance = GetRoleFinance();
        $groupdata = [];
        $result = [];
        if(!empty($this->RoleFinance['role'])){
            $groups = $this->auth->getGroups();
            $userid = \think\Session::get('admin')['userid'];
            $temp = [];
            foreach (explode(',',$this->RoleFinance['role']) as $m => $n){
                $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(2));
                if($n == 2){
                    foreach ($childlist as $k => $v){
                        if(ValueExists($dept,$v['id'])){
                            $kee = TableListSqlQuery('Field'," `parentid` = '".$v['id']."' ",'id','hdyj_auth_department');
                            $kee = implode(',',array_column($kee,'id'));
                            $temp[$kee] = $v['name'];
                            unset($kee);
                        }else{
                            $temp[$v['id']] = $v['name'];
                        }
                    }
                }else{
                    foreach ($childlist as $k => $v){
                        if(ValueExists($dept,$v['id'])){
                            if($v['id'] == $n || $v['parentid'] == $n) {
                                $kee = TableListSqlQuery('Field'," `parentid` = '".$v['id']."' ",'id','hdyj_auth_department');
                                $kee = implode(',',array_column($kee,'id'));
                                $temp[$kee] = $v['name'];
                                unset($kee);
                            }
                        }else{
                            if($v['id'] == $n || $v['parentid'] == $n) $temp[$v['id']] = $v['name'];
                        }
                    }
                }
            }
            $groupdata = $temp;
        }

        foreach ($groupdata as $key => $value) {
            $searchlist[] = ['id' => $key, 'name' => $value];
        }
        $data = ['searchlist' => $searchlist];
        $this->success('', null, $data);
    }
}
